﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using SlamCms.Areas._admin.Models;
using SlamCms.Data;
using SlamCms.Data.Repositories;
using SlamCms.Web;

namespace SlamCms.Areas._admin.Controllers
{
	public class UrlHandlerController : AdminBaseController
	{
		private readonly SlamCmsContext _slamCmsContext;
		private readonly Lazy<IUrlHandlerRepository> _urlHandlerRepository;
		private readonly Lazy<ITrackingRepository> _trackingRepository;
		private readonly Lazy<UrlHandlerRouterRegistrar> _urlHandlerRouteRegistrar; 

		public UrlHandlerController(Lazy<IUrlHandlerRepository> urlHandlerRepository, Lazy<ITrackingRepository> trackingRepository, SlamCmsContext slamCmsContext, Lazy<UrlHandlerRouterRegistrar> urlHandlerRouteRegistrar)
		{
			_urlHandlerRepository = urlHandlerRepository;
			_trackingRepository = trackingRepository;
			_slamCmsContext = slamCmsContext;
			_urlHandlerRouteRegistrar = urlHandlerRouteRegistrar;
		}

		[HttpGet]
		public ActionResult Index()
		{
			var model = new UrlHandlerIndexViewModel();
			model.UrlHandlers = _urlHandlerRepository.Value.GetAll();
			model.NotFounds = _trackingRepository.Value.GetNotFound(null);
			ViewData.Model = model;
			return View();
		}

		[HttpPost]
		public ActionResult Save(UrlHandler urlHandler)
		{
			if (urlHandler.UrlHandlerId == 0)
			{
				urlHandler.CreatedDate = DateTime.UtcNow;
				urlHandler.CreatedByUserId = _slamCmsContext.User.UserId;
			}

			urlHandler.ModifiedDate = DateTime.UtcNow;
			urlHandler.ModifiedByUserId = _slamCmsContext.User.UserId;

			_urlHandlerRepository.Value.Save(urlHandler);
			_urlHandlerRouteRegistrar.Value.RegisterRoutes(RouteTable.Routes);

			return RedirectToAction("Index");
		}

		[HttpPost]
		public ActionResult Remove(int urlHandlerId)
		{
			_urlHandlerRepository.Value.Remove(urlHandlerId);
			_urlHandlerRouteRegistrar.Value.RegisterRoutes(RouteTable.Routes);

			return Json(new { Ok = true });
		}

		[HttpPost]
		public ActionResult ClearNotFounds()
		{
			_trackingRepository.Value.ClearNotFound();
			return Json(new { Ok = true });
		}
	}
}